package com.ruoyi.web.controller.inventory;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.inventory.domain.TWarehouseTransactionItem;
import com.ruoyi.inventory.service.ITWarehouseTransactionItemService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.inventory.domain.TWarehouseStock;
import com.ruoyi.inventory.mapper.TWarehouseStockMapper;

/**
 * 出入库明细Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/system/transaction/item")
public class TWarehouseTransactionItemController extends BaseController
{
    @Autowired
    private ITWarehouseTransactionItemService tWarehouseTransactionItemService;
    
    @Autowired
    private TWarehouseStockMapper tWarehouseStockMapper;

    /**
     * 查询出入库明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:item:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWarehouseTransactionItem tWarehouseTransactionItem)
    {
        startPage();
        List<TWarehouseTransactionItem> list = tWarehouseTransactionItemService.selectTWarehouseTransactionItemList(tWarehouseTransactionItem);
        return getDataTable(list);
    }

    /**
     * 导出出入库明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:item:export')")
    @Log(title = "出入库明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TWarehouseTransactionItem tWarehouseTransactionItem)
    {
        List<TWarehouseTransactionItem> list = tWarehouseTransactionItemService.selectTWarehouseTransactionItemList(tWarehouseTransactionItem);
        ExcelUtil<TWarehouseTransactionItem> util = new ExcelUtil<TWarehouseTransactionItem>(TWarehouseTransactionItem.class);
        util.exportExcel(response, list, "出入库明细数据");
    }

    /**
     * 获取出入库明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:item:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tWarehouseTransactionItemService.selectTWarehouseTransactionItemById(id));
    }

    /**
     * 新增出入库明细
     */
    @PreAuthorize("@ss.hasPermi('system:item:add')")
    @Log(title = "出入库明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWarehouseTransactionItem tWarehouseTransactionItem)
    {
        // 1. 创建交易明细
        int itemResult = tWarehouseTransactionItemService.insertTWarehouseTransactionItem(tWarehouseTransactionItem);
        
        if (itemResult > 0) {
            // 2. 更新库存
            String direction = tWarehouseTransactionItem.getDirection();
            String partNo = tWarehouseTransactionItem.getPartNo();
            BigDecimal quantity = tWarehouseTransactionItem.getQuantity();
            String warehouseCode = "WH001"; // 默认仓库代码
            
            if ("IN".equalsIgnoreCase(direction) || "INBOUND".equalsIgnoreCase(direction) || "PURCHASE".equalsIgnoreCase(direction)) {
                // 入库 - 增加库存
                TWarehouseStock stock = new TWarehouseStock();
                stock.setPartNo(partNo);
                stock.setWarehouseCode(warehouseCode);
                
                // 查询是否存在库存记录
                TWarehouseStock queryStock = new TWarehouseStock();
                queryStock.setPartNo(partNo);
                queryStock.setWarehouseCode(warehouseCode);
                List<TWarehouseStock> stockList = tWarehouseStockMapper.selectTWarehouseStockList(queryStock);
                TWarehouseStock existingStock = stockList != null && !stockList.isEmpty() ? stockList.get(0) : null;
                if (existingStock != null) {
                    // 更新现有库存
                    existingStock.setQuantity(existingStock.getQuantity().add(quantity));
                    tWarehouseStockMapper.updateTWarehouseStock(existingStock);
                } else {
                    // 创建新库存记录
                    stock.setPartNo(partNo);
                    stock.setWarehouseCode(warehouseCode);
                    stock.setQuantity(quantity);
                    tWarehouseStockMapper.insertTWarehouseStock(stock);
                }
                
                logger.info("入库库存更新: partNo={} +{} = {}", partNo, quantity, existingStock != null ? existingStock.getQuantity().add(quantity) : quantity);
            } else if ("OUT".equalsIgnoreCase(direction) || "OUTBOUND".equalsIgnoreCase(direction) || 
                       "REPAIR".equalsIgnoreCase(direction) || "TRANSFER".equalsIgnoreCase(direction) || 
                       "SCRAP".equalsIgnoreCase(direction) || "MAINTENANCE".equalsIgnoreCase(direction)) {
                // 出库 - 减少库存
                TWarehouseStock stock = new TWarehouseStock();
                stock.setPartNo(partNo);
                stock.setWarehouseCode(warehouseCode);
                
                // 查询现有库存
                TWarehouseStock queryStock = new TWarehouseStock();
                queryStock.setPartNo(partNo);
                queryStock.setWarehouseCode(warehouseCode);
                List<TWarehouseStock> stockList = tWarehouseStockMapper.selectTWarehouseStockList(queryStock);
                TWarehouseStock existingStock = stockList != null && !stockList.isEmpty() ? stockList.get(0) : null;
                if (existingStock != null) {
                    // 检查库存是否足够
                    if (existingStock.getQuantity().compareTo(quantity) < 0) {
                        return error("库存不足: 当前库存" + existingStock.getQuantity() + ", 需要" + quantity);
                    }
                    
                    // 更新库存
                    existingStock.setQuantity(existingStock.getQuantity().subtract(quantity));
                    tWarehouseStockMapper.updateTWarehouseStock(existingStock);
                    
                    logger.info("出库库存更新: partNo={} -{} = {}", partNo, quantity, existingStock.getQuantity().subtract(quantity));
                } else {
                    return error("库存记录不存在: partNo=" + partNo + ", warehouseCode=" + warehouseCode);
                }
            } else {
                logger.warn("未知的库存方向: {}", direction);
            }
        }
        
        return itemResult > 0 ? success() : error("交易明细创建失败");
    }

    /**
     * 修改出入库明细
     */
    @PreAuthorize("@ss.hasPermi('system:item:edit')")
    @Log(title = "出入库明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWarehouseTransactionItem tWarehouseTransactionItem)
    {
        return toAjax(tWarehouseTransactionItemService.updateTWarehouseTransactionItem(tWarehouseTransactionItem));
    }

    /**
     * 删除出入库明细
     */
    @PreAuthorize("@ss.hasPermi('system:item:remove')")
    @Log(title = "出入库明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWarehouseTransactionItemService.deleteTWarehouseTransactionItemByIds(ids));
    }
}